//
//  CommentViewController.m
//  AppYing
//
//  Created by appying_wxj on 14/11/3.
//  Copyright (c) 2014年 appying_wxj. All rights reserved.
//

#import "CommentViewController.h"
#import "CommentTableViewCell.h"
@interface CommentViewController ()

@end

@implementation CommentViewController
@synthesize commentTableView;
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.userInteractionEnabled = YES;
    self.titleLab.text = @"评论界面";
    self.view.backgroundColor = [UIColor whiteColor];
    [self initCommentUI];
    
    
    
//     /**
//      计算两个时间的时间差
//      */
//    //现在的时间
//    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
//    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//    NSDate *  senddate=[NSDate date];
//    //结束时间
//    NSDate *endDate = [dateFormatter dateFromString:@"2014-11-11 10:00:00"];
//    //当前时间
//    NSDate *senderDate = [dateFormatter dateFromString:[dateFormatter stringFromDate:senddate]];
//    //得到相差秒数
//    NSTimeInterval time=[endDate timeIntervalSinceDate:senderDate];
//    
//    int days = ((int)time)/(3600*24);
//    int hours = ((int)time)%(3600*24)/3600;
//    int minute = ((int)time)%(3600*24)%3600/60;
//    
//    if (days <= 0&&hours <= 0&&minute <= 0){
////        dateContent=@"0天0小时0分钟";
//        NSString *timeStr=[[NSString alloc] initWithFormat:@"%i天%i小时%i分钟",days,hours,minute];
//        NSLog(@"------****--------%@",timeStr);
//        
//    }
//    else{
//        NSString *timeStr=[[NSString alloc] initWithFormat:@"%i天%i小时%i分钟",days,hours,minute];
//        NSLog(@"------****--------%@",timeStr);
//    }
    

    // Do any additional setup after loading the view.
}
-(void)initCommentUI{
    
    self.commentTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kScreen_Width, kScreen_Height-64-45) style:UITableViewStylePlain];
    self.commentTableView.backgroundColor = [UIColor whiteColor];
    self.commentTableView.delegate = self;
    self.commentTableView.dataSource = self;
    self.commentTableView.separatorStyle = UITableViewCellSeparatorStyleNone;// 取消表中的分割线
    
    self.commentTableView.rowHeight = 100;
    [self.view addSubview:self.commentTableView];
    
    // 颜色的设定
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef colorref = CGColorCreate(colorSpace,(CGFloat[]){ 0, 0, 0, 0 });
    
    _commentView = [[UIView alloc] initWithFrame:CGRectMake(0, kheight-45, Kwidth, 45)];
    UIImageView *BgImage =[[UIImageView alloc]initWithFrame:_commentView.bounds];
    
//    BgImage.backgroundColor = [UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1];
    BgImage.image = [UIImage imageNamed:@"image_textView@2x"];
    [_commentView addSubview:BgImage];
    [self.view addSubview:_commentView];
    
    // 返回的按钮
    _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _backButton.backgroundColor = [UIColor clearColor];
    _backButton.frame = CGRectMake(0, 0, 45, 45);
    [_backButton addTarget:self action:@selector(backUpNextView:) forControlEvents:UIControlEventTouchUpInside];
    [_commentView addSubview:_backButton];
    
    _textField = [[UITextField alloc] initWithFrame:CGRectMake(51, 8, kScreen_Width-60                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       , 30)];
    _textField.placeholder = @"  写评论";
    _textField.delegate = self;
    _textField.font = [UIFont fontWithName:nil size:12];
    
    //    _textField.keyboardType = UIKeyboardTypeEmailAddress;//点击输入框弹出的键盘样式
    _textField.clearsOnBeginEditing = NO;// 再次编辑是就清空内容
    _textField.textAlignment = NSTextAlignmentLeft;// 内容的对齐方式
    _textField.borderStyle = UITextBorderStyleNone;// 输入框的样式
    _textField.clearButtonMode = UITextFieldViewModeWhileEditing;// 编辑是出现差号
    _textField.backgroundColor = [UIColor whiteColor];// 输入框的背景颜色
    _textField.returnKeyType =UIReturnKeySend;// return按键变成send
    
    _textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    [_commentView addSubview:_textField];
    // 撰写评论的输入框
    UIImageView *image=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image_write@2x"]];
    image.frame = CGRectMake(20, 0, 20, 20);
    _textField.leftView=image;// 输入框最左边颜色的设定
    _textField.leftViewMode = UITextFieldViewModeAlways;
    
    //键盘弹出  撰写评论的界面
    _writeView = [[UIView alloc] initWithFrame:CGRectMake(0, kheight, Kwidth, 133)];
    UIImageView *writeImage =[[UIImageView alloc]initWithFrame:_writeView.bounds];
    writeImage.image = [UIImage imageNamed:@"image_twofabiao@2x"];
    writeImage.userInteractionEnabled = YES;
    [_writeView addSubview:writeImage];
    [self.view addSubview:_writeView];
    
    _textView = [[UITextView alloc] initWithFrame:CGRectMake(15, 18, Kwidth-30, 65)];
    _textView.backgroundColor = [UIColor clearColor];
    _textView.delegate = self;
    _textView.selectedRange = NSMakeRange(0, 0);// 设置光标的位置信息
    [_writeView addSubview:_textView];
    
    // 发表的按钮
    _publishButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_publishButton setBackgroundImage:[UIImage imageNamed:@"image_fabiao@2x"] forState:UIControlStateNormal];
    _publishButton.frame = CGRectMake(Kwidth-65, 18+65+5, 50, 35);
    [_writeView addSubview:_publishButton];
    
    //获取地址的按钮
    _addressButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    UIImageView *addressimage = [[UIImageView alloc] init];
    
    addressimage.frame = CGRectMake(8, 5, 15, 15);
    
    if (self.positionStrings == nil) {
        
        [_addressButton setTitle:@" 未知区域" forState:UIControlStateNormal];
        [_addressButton setTitleColor:[UIColor colorWithRed:0.14 green:0.44 blue:0.87 alpha:1] forState:UIControlStateNormal];
         addressimage.image = [UIImage imageNamed:@"image_lanweizhi@2x"];
        //        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请您在您的设置中设置您的位置服务信息" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        //        [alertView show];
    }else {
        
        addressimage.image = [UIImage imageNamed:@"image_weizhi@2x"];
        [_addressButton setTitleColor:[UIColor colorWithRed:0.54 green:0.54 blue:0.54 alpha:1] forState:UIControlStateNormal];
        [_addressButton setTitle:[NSString stringWithFormat:@"     %@",self.positionStrings] forState:UIControlStateNormal];
    }
    _addressButton.titleLabel.font = [UIFont systemFontOfSize: 12.0];// 按钮上字体大小的设置
    [_addressButton.layer setMasksToBounds:YES];
    [_addressButton.layer setCornerRadius:13.0]; //设置矩形四个圆角半径
    [_addressButton.layer setBorderWidth:1.0];
    [_addressButton.layer setBorderColor:colorref];//边框颜色
    _addressButton.backgroundColor = [UIColor colorWithRed:0.85 green:0.85 blue:0.85 alpha:1];
    _addressButton.frame = CGRectMake(15, 18+65+10, 100, 25);
    [_addressButton addTarget:self action:@selector(addressButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [_writeView addSubview:_addressButton];
    
    [_addressButton addSubview:addressimage];
    
    
    
}
#pragma mark~~~~~~~~~~ UITableView dataSource delegate ~~~~~~~~~
// 设置区的数量
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
//// 设置区头的标题
//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
//{
//    return [NSString stringWithFormat:@"第%d区的区头",section];
//}
//设置区头高度的方法    默认高度20
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 80;
}
// 设置有多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 20;
}
//点击单元格上按钮的方法   点击按钮的方法
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"点击了第%d区第%d行的小按钮",indexPath.section,indexPath.row);
}
// 设置单元格
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identify = @"cell";
    CommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
    
    if(cell == nil)
    {
        cell = [[CommentTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify];
    }
    else{
        while ([cell.contentView.subviews lastObject]!=nil) {
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    cell.userInteractionEnabled = YES;
    
    
    cell.addressLabel.text = @"来自 上海 的网友";
    cell.praiseImageView.image = [UIImage imageNamed:@"image_zan2@2x"];

    return cell;
}
// 自定义区头的view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, 80)];
    titleView.backgroundColor = [UIColor whiteColor];
    
    // 文章的标题
    UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, kScreen_Width-20, 55)];
    titleLab.text = @"触控今天给了大家很多的开发框架，有cocos2d-x，cocos2d-js，quick等。如果要跨浏览器可以用cocos2d-js";
    titleLab.numberOfLines = 0;// 0表示可以显示多行
    [titleView addSubview:titleLab];
    
    // 评论
    UILabel *CommentLab = [[UILabel alloc] initWithFrame:CGRectMake(10, 60, 40, 10)];
    CommentLab.text = @"评论";
    CommentLab.font = [UIFont systemFontOfSize:12];
    CommentLab.textColor = [UIColor lightGrayColor];
    [titleView addSubview:CommentLab];

    // 获取现在的时间
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd"];
    NSString *  morelocationString=[dateformatter stringFromDate:senddate];
    NSLog(@"  现在的时间是 ：%@",morelocationString);

    // 时间
    UILabel *timeLab = [[UILabel alloc] initWithFrame:CGRectMake(60, 60, 100, 10)];
    timeLab.text = [NSString stringWithFormat:@"%@",morelocationString];
    timeLab.font = [UIFont systemFontOfSize:12];
    timeLab.textColor = [UIColor lightGrayColor];
    [titleView addSubview:timeLab];
    
    UIImageView *imageLine = [[UIImageView alloc] initWithFrame:CGRectMake(10, 79.5, kScreen_Width-20, 0.5)];
    imageLine.backgroundColor = [UIColor lightGrayColor];
    [titleView addSubview:imageLine];
    
    return titleView;
}
// 点击单元格 调用单元格方法  点击(选中) 单元格调用的方法 返回值类型(void) 取消选中
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%d行",indexPath.row);
    //    取消选中
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#pragma mark~~~~~~~~UITextViewDelegate~~~~~~~~~~~~~
- (void)textViewDidBeginEditing:(UITextView *)textView {
    [_publishButton setBackgroundImage:[UIImage imageNamed:@"image_onefabiao@2x"] forState:UIControlStateNormal];
}
- (void)textViewDidEndEditing:(UITextView *)textView{
    [_publishButton setBackgroundImage:[UIImage imageNamed:@"image_fabiao@2x"] forState:UIControlStateNormal];
}

#pragma mark-- UITextField delegate
-(CGRect)textRectForBounds:(CGRect)bounds{
    return CGRectInset(bounds, -1, 0);
}
-(CGRect)editingRectForBounds:(CGRect)bounds{
    return CGRectInset(bounds, -1, 0);
}
//开始编辑时触发，文本字段将成为first responder
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    _textView.text = _textField.text;
    //注册通知,监听键盘弹出事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShows:)
                                                 name:UIKeyboardWillShowNotification object:nil];
    
    //注册通知,监听键盘消失事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHidden)
                                                 name:UIKeyboardWillHideNotification object:nil];
    
    
}
// 点击done（发送）  键盘下去
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [_textField resignFirstResponder];    //主要是[receiver resignFirstResponder]在哪调用就能把receiver对应的键盘往下收
    return YES;
}

//限制只能输入一定长度的字符
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    //string就是此时输入的那个字符 textField就是此时正在输入的那个输入框 返回YES就是可以改变输入框的值 NO相反
    
    if ([string isEqualToString:@"n"])//按会车可以改变
    {
        return YES;
    }
    
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //得到输入框的内容
    
    if (_textField == textField)//判断是否时我们想要限定的那个输入框
    {
        if ([toBeString length] > 70) { //如果输入框内容大于20则弹出警告
            textField.text = [toBeString substringToIndex:70];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"超过最大字数不能输入了" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [alert show];
            return NO;
        }
    }
    return YES;
}

#pragma mark-- 键盘弹出的方法
// 键盘弹出时
-(void)keyboardDidShows:(NSNotification *)notification{
    [_commentView setHidden:YES];
    _textView.text = _textField.text;
    
    //获取键盘高度
    NSValue *keyboardObject = [[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    CGRect keyboardRect;
    
    [keyboardObject getValue:&keyboardRect];
    
    //调整放置有textView的view的位置
    //设置动画
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    
    [_writeView setHidden:NO];
    // 设置撰写评论的view 向上移动
    //    int autoHeight = kheight -50 - keyboardRect.size.height+10;//高度
    //    _commentView.frame = CGRectMake(0, autoHeight, kheight-29, 40);
    
    
    
    int autoHeight = keyboardRect.size.height;//高度
    _writeView.frame = CGRectMake(0, kheight -132 - autoHeight, kScreen_Width, 133);
    
    self.commentTableView.frame = CGRectMake(0, 64, kScreen_Width, kScreen_Height-64-autoHeight-133);
    [UIView commitAnimations];
    
}
//键盘消失时
-(void)keyboardDidHidden{
    [_commentView setHidden:NO];
    [_writeView setHidden:YES];
    self.commentTableView.frame = CGRectMake(0, 64, kScreen_Width, kScreen_Height-64-45);
    _commentView.frame = CGRectMake(0, kScreen_Height-45, kScreen_Width, 45);
    _textField.text = _textView.text;
}

#pragma mark-- ButtonClick
// 返回按钮的点击事件
-(void)backUpNextView:(UIButton *)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}
// 键盘消失的方法
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
// 获取地理位置按钮的点击方法
-(void)addressButtonClick:(UIButton *)sender{
    
    //        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请您在您的设置中设置您的位置服务信息" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    //        [alertView show];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
